﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using SubSonic.Sugar;
using System.Security;
using MediaMonitor.Common;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Ionic.Zip;



namespace MediaMonitor.Users
{
    public partial class Report_News : Adex.BasePage
    {
        int mediaTypeCode = 0;
        string mediaCodes = "", categoryCode = "", productCode="";
        int sectorCode = 0, subSectorCode = 0;
        int advertiserCode = 0;
        private int sectionCode = 0, newsTypeCode = 0;
        private string newsMediaType = "";
        int sPrice = 0, ePrice = 0;
        bool firstAppearanceOnly = false;
        bool downloadOnly = false;
        bool downloadOnlyProduct = false;
        string cols = "", days="";
        private iTextSharp.text.Font PDF_FONT_DEFAULT;
        private iTextSharp.text.Font PDF_FONT_TH;
        private iTextSharp.text.Font PDF_FONT_BOLD;
        private iTextSharp.text.Font PDF_FONT_GRAY;
        private iTextSharp.text.Font PDF_FONT_LIGHTGRAY;
        private iTextSharp.text.Font PDF_FONT_TITLE;
        private iTextSharp.text.Font PDF_FONT_HEADING;
        private iTextSharp.text.Font PDF_FONT_HEADING_GRAY;
        private iTextSharp.text.Font PDF_FONT_BIG;
        private iTextSharp.text.Font PDF_FONT_BIG_BOLD;
        private iTextSharp.text.Font PDF_FONT_NAV;

        protected void Page_Init(object sender, EventArgs e)
        {
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            string fontpath = Server.MapPath("../");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "Fonts/KOKILA.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font Kokila = new Font(customfont, 44, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_TITLE = Kokila;
            BaseFont customfontarial = BaseFont.CreateFont(fontpath + "Fonts/ARIAL.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font ARIAL = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIAL16 = new Font(customfontarial, 16, Font.BOLD, BaseColor.BLACK);
            Font ARIALNORMAL11 = new Font(customfontarial, 11, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_DEFAULT = ARIALNORMAL11;
            PDF_FONT_TH = ARIAL;
            PDF_FONT_BOLD = ARIAL16;
            PDF_FONT_GRAY = new Font(bf, 14, Font.NORMAL, BaseColor.DARK_GRAY);
            PDF_FONT_LIGHTGRAY = new Font(bf, 15, Font.NORMAL, new BaseColor(System.Drawing.Color.FromArgb(141, 141, 141)));
            PDF_FONT_HEADING = new Font(bf, 16, Font.BOLD, BaseColor.WHITE);
            PDF_FONT_HEADING_GRAY = new Font(bf, 18, Font.BOLD, BaseColor.GRAY);
            PDF_FONT_BIG = new Font(bf, 14, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_BIG_BOLD = new Font(bf, 14, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_NAV = new Font(bf, 14, Font.BOLD, BaseColor.RED);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(IsPostBack))
            {
                FillReport();
            }
            downloadOnly = Utility.ToBool(Utility.GetRequestedVal("down", "0"));
            downloadOnlyProduct = Utility.ToBool(Utility.GetRequestedVal("downpro", "0"));
            if (downloadOnly)
            {
                pnlCategory.Visible = true;
            }
            else
            {
                pnlCategory.Visible = false;
            }
            if (downloadOnlyProduct)
            {
                PnlProduct.Visible = true;
               
            }
            else
            {
                PnlProduct.Visible = false;
               
            }
        }

        private void FillReport()
        {

            string sDate = Utility.GetRequestedVal("sd", "01_01_2000").Replace("_", "/");
            string eDate = Utility.GetRequestedVal("ed", "01_01_2000").Replace("_", "/");
            mediaTypeCode = Utility.ToInt(Utility.GetRequestedVal("mtc", "0"));
            bool searchFromAllMedia = Utility.ToBool(Utility.GetRequestedVal("mc", "false"));
            mediaCodes = searchFromAllMedia == false ? Session["SearchMediaCodes_outdoor"].ToString() : "";
            sectorCode = Utility.ToInt(Utility.GetRequestedVal("s", "0"));
            subSectorCode = Utility.ToInt(Utility.GetRequestedVal("ss", "0"));
            categoryCode =Utility.GetRequestedVal("cc", "");
            advertiserCode = Utility.ToInt(Utility.GetRequestedVal("adv", "0"));
            productCode = Utility.GetRequestedVal("prod", "");
            sectionCode = Utility.ToInt(Utility.GetRequestedVal("sc", "0"));
            newsTypeCode = Utility.ToInt(Utility.GetRequestedVal("ntc", "0"));
            newsMediaType = Utility.GetRequestedVal("nmt", "");
            sPrice = Utility.ToInt(Utility.GetRequestedVal("sp", "0"));
            ePrice = Utility.ToInt(Utility.GetRequestedVal("ep", "0"));
            firstAppearanceOnly = Utility.ToBool(Utility.GetRequestedVal("fa", "0"));
            days = Utility.GetRequestedVal("days", "");
            objDS.SelectParameters["userID"].DefaultValue = AppUser.CurrUserID.ToString();
            objDS.SelectParameters["sDate"].DefaultValue = sDate.ToString();
            objDS.SelectParameters["eDate"].DefaultValue = eDate.ToString();
            objDS.SelectParameters["mediaTypeCode"].DefaultValue = mediaTypeCode.ToString();
            objDS.SelectParameters["mediaCodes"].DefaultValue = mediaCodes;
            objDS.SelectParameters["sectorCode"].DefaultValue = sectorCode.ToString();
            objDS.SelectParameters["subSectorCode"].DefaultValue = subSectorCode.ToString();
            objDS.SelectParameters["categoryCode"].DefaultValue = categoryCode.ToString();
            objDS.SelectParameters["advertiserCode"].DefaultValue = advertiserCode.ToString();
            objDS.SelectParameters["productCode"].DefaultValue = productCode.ToString();
            objDS.SelectParameters["sPrice"].DefaultValue = sPrice.ToString();
            objDS.SelectParameters["ePrice"].DefaultValue = ePrice.ToString();
            objDS.SelectParameters["sectionCode"].DefaultValue = sectionCode.ToString();
            objDS.SelectParameters["newsTypeCode"].DefaultValue = newsTypeCode.ToString();
            objDS.SelectParameters["newsMediaType"].DefaultValue = newsMediaType;
            objDS.SelectParameters["fa"].DefaultValue = firstAppearanceOnly.ToString();
            objDS.SelectParameters["days"].DefaultValue = days.ToString();
            radGrid.DataSourceID = "objDS";
            radGrid.DataBind();
        }
        protected void ObjDS_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (!e.ExecutingSelectCount)
            {
                e.Arguments.MaximumRows = radGrid.PageSize;
                e.InputParameters.Add("e", e);
            }
        }
        protected void btnExport_Clicked(object sender, EventArgs e)
        {
            GetPDF();
        }

        #region PDF Utility Funcs

        private string Grid2HTML(GridView grid)
        {
            HtmlForm form = new HtmlForm();
            form.Controls.Add(grid);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
            form.Controls[0].RenderControl(hTextWriter);
            string html = sw.ToString();
            return html;
        }

        private PdfPTable GetPDFTable(DataTable dt, Int32 excludecolumn)
        {
            if (dt.Rows.Count == 0)
                return new PdfPTable(0);

            int columnCount = dt.Columns.Count - excludecolumn;
            int rowCount = dt.Rows.Count;
            int tableRows = rowCount + 3;
            iTextSharp.text.pdf.PdfPTable gridTable = new PdfPTable(columnCount);
            gridTable.WidthPercentage = 100;
            var colWidthPercentages = new[] { 10f, 10f, 20f, 30f, 20f, 10f };
            gridTable.SetWidths(colWidthPercentages);
            //add headers
            PdfPCell[] arrTh = new PdfPCell[columnCount];
            for (int i = 1; i < columnCount; i++)
            {

                string header = "";
                string[] heads = SubSonic.Sugar.Strings.ToWords(dt.Columns[i].ColumnName);
                foreach (string head in heads)
                    header += head + " ";

                if (i == columnCount - 1)
                {
                    header = header.Trim() + "              Image";
                }
                {
                    header = header.Trim();
                }
                arrTh[i - 1] = new PdfPCell();
                arrTh[i - 1].AddElement(new Chunk(header, PDF_FONT_BOLD));
                arrTh[i - 1].Border = 0;
                arrTh[i - 1].BorderColorLeft = BaseColor.WHITE;
                arrTh[i - 1].BorderWidthTop = 1f;
                arrTh[i - 1].BorderWidthBottom = 1f;
                if (i == 1)
                {
                    arrTh[i - 1].BorderWidthLeft = 1f;
                    arrTh[i - 1].BorderColorLeft = BaseColor.BLACK;
                    arrTh[i - 1].PaddingLeft = 5f;
                }
                if (i == columnCount - 1)
                {
                    arrTh[i - 1].BorderWidthRight = 1f;
                    arrTh[i - 1].BorderColorRight = BaseColor.BLACK;
                    arrTh[i - 1].Colspan = 2;
                }
                arrTh[i - 1].PaddingTop = 10f;
                arrTh[i - 1].PaddingBottom = 20f;
            }
            arrTh[columnCount - 1] = new PdfPCell();
            gridTable.Rows.Add(new PdfPRow(arrTh));
            int rowIndex = 0;
            foreach (DataRow dr in dt.Rows)
            {
                PdfPCell[] arrTd = new PdfPCell[columnCount];
                int colIndex = 1;
                for (colIndex = 1; colIndex < columnCount; colIndex++)
                {

                    arrTd[colIndex - 1] = new PdfPCell();
                    arrTd[colIndex - 1].AddElement(new Chunk(Utility.IsNullStr(dt.Rows[rowIndex][colIndex], "")));
                    arrTd[colIndex - 1].Border = 0;
                }

                arrTd[colIndex - 1] = new PdfPCell();
                string croppedImagePath = Server.MapPath("~") + "\\News\\Cropped\\" + dt.Rows[rowIndex]["CropPicture"].ToString();
                if (excludecolumn == 2)//products
                {
                    string fullImagePath = Server.MapPath("~") + "\\News\\FullPage\\" + dt.Rows[rowIndex]["FullPagePicture"].ToString();
                    if ((File.Exists(croppedImagePath)) || (File.Exists(fullImagePath)))  //cropped Image  OR full Image
                    {

                        Chunk cImage = new Chunk(iTextSharp.text.Image.GetInstance(Server.MapPath("~") + "\\images\\siteimages\\view.jpg"), 0, 0, false);
                        Anchor detail = new Anchor(cImage);
                        detail.Reference = "#" + dt.Rows[rowIndex]["NewsLogID"].ToString();
                        Paragraph p1 = new Paragraph();
                        p1.Add(detail);
                        arrTd[colIndex - 1].AddElement(p1);
                    }
                    else
                    {
                        Paragraph p1 = new Paragraph();
                        p1.Add("");
                        arrTd[colIndex - 1].AddElement(p1);
                    }
                }
                else //news
                {
                    if (File.Exists(croppedImagePath))  //cropped Image
                    {
                        Chunk cImage = new Chunk(iTextSharp.text.Image.GetInstance(Server.MapPath("~") + "\\images\\siteimages\\view.jpg"), 0, 0, false);
                        Anchor detail = new Anchor(cImage);
                        detail.Reference = "#" + dt.Rows[rowIndex]["NewsLogID"].ToString();
                        Paragraph p1 = new Paragraph();
                        p1.Add(detail);
                        arrTd[colIndex - 1].AddElement(p1);
                    }
                    else
                    {
                        Paragraph p1 = new Paragraph();
                        p1.Add("");
                        arrTd[colIndex - 1].AddElement(p1);
                    }
                }
                arrTd[colIndex - 1].Border = 0;
                arrTd[colIndex - 1].PaddingTop = 10f;
                gridTable.Rows.Add(new PdfPRow(arrTd));
                rowIndex++;
            }

            return gridTable;
        }
        private PdfPTable GetPDFTablePublication(DataTable dt)
        {
            if (dt.Rows.Count == 0)
                return new PdfPTable(0);
            int columnCount = dt.Columns.Count;
            int rowCount = dt.Rows.Count;
            int tableRows = rowCount + 3;
            iTextSharp.text.pdf.PdfPTable gridTable = new PdfPTable(columnCount);
            gridTable.WidthPercentage = 100;

            //Set the table width percentage to 100
            var colWidthPercentages = new[] { 20f, 15f, 20f, 40f, 5f };
            gridTable.SetWidths(colWidthPercentages);
            PdfPCell[] arrTh = new PdfPCell[columnCount];
            for (int i = 1; i < columnCount; i++)
            {
                string header = "";
                string[] heads = SubSonic.Sugar.Strings.ToWords(dt.Columns[i].ColumnName);
                foreach (string head in heads)
                    header += head + " ";
                header = header.Trim();
                arrTh[i - 1] = new PdfPCell();
                arrTh[i - 1].AddElement(new Chunk(header, PDF_FONT_BOLD));
                arrTh[i - 1].Border = 0;
                arrTh[i - 1].BorderColorLeft = BaseColor.WHITE;
                arrTh[i - 1].BorderWidthTop = 1f;
                arrTh[i - 1].BorderWidthBottom = 1f;
                if (i == 1)
                {
                    arrTh[i - 1].BorderWidthLeft = 1f;
                    arrTh[i - 1].BorderColorLeft = BaseColor.BLACK;
                    arrTh[i - 1].PaddingLeft = 5f;
                }
                if (i == columnCount - 1)
                {
                    arrTh[i - 1].BorderWidthRight = 1f;
                    arrTh[i - 1].BorderColorRight = BaseColor.BLACK;
                    arrTh[i - 1].Colspan = 2;
                }
                arrTh[i - 1].PaddingTop = 10f;
                arrTh[i - 1].PaddingBottom = 20f;
            }

            arrTh[columnCount - 1] = new PdfPCell();
            gridTable.Rows.Add(new PdfPRow(arrTh));
            int rowIndex = 0;
            foreach (DataRow dr in dt.Rows)
            {
                PdfPCell[] arrTd = new PdfPCell[columnCount];
                int colIndex = 1;
                for (colIndex = 1; colIndex < columnCount; colIndex++)
                {

                    arrTd[colIndex - 1] = new PdfPCell();
                    arrTd[colIndex - 1].Border = 0;
                    if (colIndex == columnCount - 1) //NewLink
                    {
                        BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                        Font link = new Font(bf1, 12, Font.ITALIC, new BaseColor(System.Drawing.Color.FromArgb(0, 0, 255)));
                        Chunk path = new Chunk(dt.Rows[rowIndex][colIndex].ToString(), link);
                        path.SetUnderline(1f, -2f);
                        Anchor serverpath = new Anchor(path);
                        serverpath.Reference = dt.Rows[rowIndex][colIndex].ToString();
                        Paragraph p1 = new Paragraph();
                        p1.Add(serverpath);
                        arrTd[colIndex - 1].AddElement(p1);
                    }
                    else
                    {
                        arrTd[colIndex - 1].AddElement(new Chunk(Utility.IsNullStr(dt.Rows[rowIndex][colIndex], "")));
                    }
                }

                arrTd[colIndex - 1] = new PdfPCell();
                arrTd[colIndex - 1].Border = 0;
                arrTd[colIndex - 1].PaddingTop = 10f;
                gridTable.Rows.Add(new PdfPRow(arrTd));
                rowIndex++;
            }

            return gridTable;
        }


        private void HTML2PDF(Document pdfDoc, PdfWriter writer, string HTMLCode)
        {
            HttpContext context = HttpContext.Current;
            //Render PlaceHolder to temporary stream 
            System.IO.StringWriter stringWrite = new StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            /********************************************************************************/
            //Try adding source strings for each image in content
            string tempPostContent = getImage(HTMLCode);
            /*********************************************************************************/

            StringReader reader = new StringReader(tempPostContent);
            //Create PDF document 
            HTMLWorker parser = new HTMLWorker(pdfDoc);
            try
            {
                //Parse Html and dump the result in PDF file
                parser.Parse(reader);
            }
            catch (Exception ex)
            {
                //Display parser errors in PDF. 
                Paragraph paragraph = new Paragraph("Error!" + ex.Message);
                Chunk text = paragraph.Chunks[0] as Chunk;
                if (text != null)
                {
                    text.Font.Color = BaseColor.RED;
                }
                pdfDoc.Add(paragraph);
            }

        }


        public string getImage(string input)
        {
            if (input == null)
                return string.Empty;
            string tempInput = input;
            string pattern = @"<img(.|\n)+?>";
            string src = string.Empty;
            HttpContext context = HttpContext.Current;

            //Change the relative URL's to absolute URL's for an image, if any in the HTML code.
            foreach (Match m in Regex.Matches(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.RightToLeft))
            {
                if (m.Success)
                {
                    string tempM = m.Value;
                    string pattern1 = "src=[\'|\"](.+?)[\'|\"]";
                    Regex reImg = new Regex(pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    Match mImg = reImg.Match(m.Value);

                    if (mImg.Success)
                    {
                        src = mImg.Value.ToLower().Replace("src=", "").Replace("\"", "");

                        if (src.ToLower().Contains("http://") == false)
                        {
                            //Insert new URL in img tag
                            src = "src=\"" + context.Request.Url.Scheme + "://" +
                                context.Request.Url.Authority + src + "\"";
                            try
                            {
                                tempM = tempM.Remove(mImg.Index, mImg.Length);
                                tempM = tempM.Insert(mImg.Index, src);

                                //insert new url img tag in whole html code
                                tempInput = tempInput.Remove(m.Index, m.Length);
                                tempInput = tempInput.Insert(m.Index, tempM);
                            }
                            catch (Exception e)
                            {

                            }
                        }
                    }
                }
            }
            return tempInput;
        }

        string getSrc(string input)
        {
            string pattern = "src=[\'|\"](.+?)[\'|\"]";
            System.Text.RegularExpressions.Regex reImg = new System.Text.RegularExpressions.Regex(pattern,
                System.Text.RegularExpressions.RegexOptions.IgnoreCase |

    System.Text.RegularExpressions.RegexOptions.Multiline);
            System.Text.RegularExpressions.Match mImg = reImg.Match(input);
            if (mImg.Success)
            {
                return mImg.Value.Replace("src=", "").Replace("\"", ""); ;
            }

            return string.Empty;
        }

        string GetCurrency(string currency)
        {
            switch (AppUser.GetCountry())
            {
                case 58:
                    {
                        return "RD$ " + currency;
                    }
                case 218:
                    {
                        return "TT$ " + currency;
                    }

            }

            return "";
        }
        #endregion

        #region PDF Generation

        private void GetPDF()
        {

            string sDate = Utility.GetRequestedVal("sd", "01_01_2000").Replace("_", "/");
            string eDate = Utility.GetRequestedVal("ed", "01_01_2000").Replace("_", "/");
            mediaTypeCode = Utility.ToInt(Utility.GetRequestedVal("mtc", "0"));
            bool searchFromAllMedia = Utility.ToBool(Utility.GetRequestedVal("mc", "false"));
            mediaCodes = searchFromAllMedia == false ? Session["SearchMediaCodes_outdoor"].ToString() : "";
            sectorCode = Utility.ToInt(Utility.GetRequestedVal("s", "0"));
            subSectorCode = Utility.ToInt(Utility.GetRequestedVal("ss", "0"));
            categoryCode = Utility.GetRequestedVal("cc", "");
            advertiserCode = Utility.ToInt(Utility.GetRequestedVal("adv", "0"));
            productCode = Utility.GetRequestedVal("prod", "");
            sectionCode = Utility.ToInt(Utility.GetRequestedVal("sc", "0"));
            newsTypeCode = Utility.ToInt(Utility.GetRequestedVal("ntc", "0"));
            newsMediaType = Utility.GetRequestedVal("nmt", "");
            sPrice = Utility.ToInt(Utility.GetRequestedVal("sp", "0"));
            ePrice = Utility.ToInt(Utility.GetRequestedVal("ep", "0"));
            firstAppearanceOnly = Utility.ToBool(Utility.GetRequestedVal("fa", "0"));
            Sector sector = new Sector(sectorCode);
            SubSector subSector = new SubSector(subSectorCode);
            Category category = new Category(0);
            Advertiser advertiser = new Advertiser(advertiserCode);
            Product product = new Product(0);
            NewsSection section = new NewsSection(sectionCode);

            string newsTypeName = Utility.ToStr(NewsLog.Query().DISTINCT().SetSelectList("NewsTypeName").WHERE("NewsTypeCode", newsTypeCode).ExecuteScalar());
            DataSet dsNewsPDF = new Common.ReportFuncs().GetReportNews_PDF(AppUser.CurrUserID, Utility.ToDateTime(sDate as object), Utility.ToDateTime(eDate as object), mediaTypeCode, mediaCodes, sectorCode, subSectorCode, categoryCode, advertiserCode, productCode, sPrice, ePrice, sectionCode, newsTypeCode, newsMediaType, firstAppearanceOnly,days);
            if ((dsNewsPDF.Tables[0].Rows.Count > 0) || (dsNewsPDF.Tables[1].Rows.Count > 0) || (dsNewsPDF.Tables[2].Rows.Count > 0) || (dsNewsPDF.Tables[3].Rows.Count > 0) || (dsNewsPDF.Tables[4].Rows.Count > 0))
            {
                DataTable dtProd = dsNewsPDF.Tables[0];
                DataTable dtProdDetail = dsNewsPDF.Tables[1];
                DataTable dtPublication = dsNewsPDF.Tables[2];
                DataTable dtNews = dsNewsPDF.Tables[3];
                DataTable dtNewsDetail = dsNewsPDF.Tables[4];
                Company company = new Company(AppUser.CurrentUser.CompanyCode);
                string pdfImg1 = "_DEFAULT_1.JPG";
                string pdfImg2 = "_DEFAULT_2.JPG";

                string TemplateName = " Default";
                if (company.NewsTemplate != null)
                    TemplateName = " " + company.NewsTemplate.TemplateName;
                string fileName = "Flash Informativo" + TemplateName + " " + DateTime.Now.ToString("dd - MM - yy");

                if (company.NewsTemplateID > 0)
                {
                    pdfImg1 = company.NewsTemplate.Picture1;
                    pdfImg2 = company.NewsTemplate.Picture2;
                }

                string homeImageFilePath = Server.MapPath("~") + "\\images\\templates\\" + pdfImg1;
                string subImageFilePath = Server.MapPath("~") + "\\images\\templates\\" + pdfImg2;
                // PDF GENERATEION - start

                iTextSharp.text.Image bgHomePage = iTextSharp.text.Image.GetInstance(homeImageFilePath);
                iTextSharp.text.Image bgSubPage = iTextSharp.text.Image.GetInstance(subImageFilePath);
                iTextSharp.text.Rectangle PdfPageSize = new iTextSharp.text.Rectangle(bgHomePage.Width, bgHomePage.Height);
                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PdfPageSize);

                bgHomePage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;
                bgSubPage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;

                bgHomePage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);
                bgSubPage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);

                bgHomePage.SetAbsolutePosition(0, 0);
                bgSubPage.SetAbsolutePosition(0, 0);

                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

                // Our custom Header and Footer is done using Event Handler
                TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter();
                writer.PageEvent = PageEventHandler;

                // Define the page header
                pdfDoc.Open();
                CreatePDFPage_Home(pdfDoc, writer, bgHomePage, "MONITORING OF PRINT AND INTERNET NEWS");
                CreatePDFPage_Criteria(pdfDoc, writer, bgSubPage, Utility.ToDateTime(sDate), Utility.ToDateTime(eDate), advertiser.AdvertiserName, sector.SectorName, subSector.SubSectorName, category.CategoryName, section.SectionName);
                CreatePDFPage_ProductList(pdfDoc, writer, bgSubPage, dtProd);
                CreatePDFPage_PublicationList(pdfDoc, writer, bgSubPage, dtPublication);
                CreatePDFPage_NewsList(pdfDoc, writer, bgSubPage, dtNews);
                CreatePDFPage_ProductDetailList(pdfDoc, writer, bgSubPage, dtProdDetail);
                CreatePDFPage_NewsDetailList(pdfDoc, writer, bgSubPage, dtNewsDetail);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
                // PDF GENERATION - end
            }
            else
            {
                string script = "alert(\"No Record Exists!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

            }
        }
        private void CreatePDFPage_Home(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, string title)
        {
            pdfDoc.NewPage();
            PdfContentByte pcb = writer.DirectContentUnder;
            pcb.AddImage(bgImage);
            Paragraph pTitle = new Paragraph(44.0f, "\n\n\n\n\n" + title, PDF_FONT_TITLE);
            pTitle.Alignment = Rectangle.ALIGN_CENTER;
            Paragraph pDate = new Paragraph(18.0f, "\n\n\n\n\n\n\n\n\n\n\n\n\n" + DateTime.Now.ToString("dd MMMM yyyy"), PDF_FONT_HEADING_GRAY);
            pdfDoc.Add(pTitle);
            pdfDoc.Add(pDate);

        }

        private void CreatePDFPage_Criteria(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DateTime sDate, DateTime eDate, string advertiser, string sector, string subSector, string category, string section)
        {
            advertiser = Utility.IsNullStr(advertiser, "All");
            sector = Utility.IsNullStr(sector, "All");
            subSector = Utility.IsNullStr(subSector, "All");
            category = Utility.IsNullStr(category, "All");
            section = Utility.IsNullStr(section, "All");
            pdfDoc.NewPage();
            PdfContentByte pcb1 = writer.DirectContentUnder;
            pcb1.AddImage(bgImage);
            Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nUSER SELECTION", PDF_FONT_HEADING);
            pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
            pPageHeading.IndentationLeft = 330f;
            pPageHeading.SpacingAfter = 16f;
            pdfDoc.Add(pPageHeading);

            Paragraph pDate = new Paragraph("From: " + sDate.ToString("dd MMMM, yyyy") + " to: " + eDate.ToString("dd MMMM, yyyy"), PDF_FONT_LIGHTGRAY);
            pDate.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
            pDate.IndentationLeft = 330f;

            pdfDoc.Add(pDate);

            Paragraph pCriteria = new Paragraph();
            pCriteria.Add(new Chunk("\n\n\n Sector:", PDF_FONT_BIG_BOLD));
            pCriteria.Add(new Chunk("\n " + sector, PDF_FONT_BIG));
            pCriteria.Add(new Chunk("\n\n SubSector:", PDF_FONT_BIG_BOLD));
            pCriteria.Add(new Chunk("\n" + subSector, PDF_FONT_BIG));
            pCriteria.Add(new Chunk("\n\n Category:", PDF_FONT_BIG_BOLD));
            pCriteria.Add(new Chunk("\n " + category, PDF_FONT_BIG));
            pCriteria.Add(new Chunk("\n\n Section:", PDF_FONT_BIG_BOLD));
            pCriteria.Add(new Chunk("\n " + section, PDF_FONT_BIG));
            pCriteria.Add(new Chunk("\n\n Advertiser:", PDF_FONT_BIG_BOLD));
            pCriteria.Add(new Chunk("\n " + advertiser, PDF_FONT_BIG));
            pCriteria.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
            pdfDoc.Add(pCriteria);

        }


        private void CreatePDFPage_ProductList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtProds)
        {

            if (dtProds.Rows.Count > 0)
            {
                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nPRODUCTS\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "Products";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                Int32 excludecolumn = 2;
                PdfPTable prodTable = GetPDFTable(dtProds, excludecolumn);
                pdfDoc.Add(prodTable);

            }

        }


        private void CreatePDFPage_PublicationList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtPubs)
        {

            if (dtPubs.Rows.Count > 0)
            {

                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nPUBLICATIONS\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "Publications";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                PdfPTable pubsTable = GetPDFTablePublication(dtPubs);
                pdfDoc.Add(pubsTable);

            }

        }


        private void CreatePDFPage_NewsList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtNews)
        {

            if (dtNews.Rows.Count > 0)
            {

                pdfDoc.NewPage();
                PdfContentByte pcb1 = writer.DirectContentUnder;
                pcb1.AddImage(bgImage);
                Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nNEWS\n\n\n\n", PDF_FONT_HEADING);
                pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                pPageHeading.IndentationLeft = 330f;
                pdfDoc.Add(pPageHeading);
                Anchor prodAnchor = new Anchor(".");
                prodAnchor.Name = "News";
                Paragraph p = new Paragraph();
                p.Add(prodAnchor);
                pdfDoc.Add(p);
                Int32 excludecolumn = 1;
                PdfPTable newsTable = GetPDFTable(dtNews, excludecolumn);

                pdfDoc.Add(newsTable);

            }

        }


        private void CreatePDFPage_ProductDetailList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtProdDetail)
        {

            foreach (DataRow dr in dtProdDetail.Rows)
            {

                string croppedImagePath = Server.MapPath("~") + "\\News\\Cropped\\" + dr["CropPicture"].ToString();
                string fullImagePath = Server.MapPath("~") + "\\News\\FullPage\\" + dr["FullPagePicture"].ToString();
                if ((File.Exists(croppedImagePath)) || (File.Exists(fullImagePath))) //cropped Image OR full Image
                {
                    pdfDoc.NewPage();
                    PdfContentByte pcb1 = writer.DirectContentUnder;
                    pcb1.AddImage(bgImage);
                    Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nPRODUCT: " + dr["ProductName"] + "\n\n", PDF_FONT_HEADING);
                    pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                    pPageHeading.IndentationLeft = 330f;

                    pdfDoc.Add(pPageHeading);

                    Anchor prodAnchor = new Anchor(".");
                    prodAnchor.Name = dr["NewsLogID"].ToString();
                    Paragraph p = new Paragraph();
                    p.Add(prodAnchor);
                    pdfDoc.Add(p);

                    PdfPTable pdfTable = new PdfPTable(9);
                    pdfTable.WidthPercentage = 100;

                    var colWidthPercentages = new[] { 7f, 20f, 6f, 17f, 10f, 12f, 8f, 12f, 8f };
                    pdfTable.SetWidths(colWidthPercentages);
                    PdfPCell[] arrTd1 = new PdfPCell[9];

                    arrTd1[0] = new PdfPCell();

                    arrTd1[0].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[0].AddElement(new Chunk("Category:", PDF_FONT_TH));
                    arrTd1[1] = new PdfPCell();
                    arrTd1[1].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[1].AddElement(new Chunk(dr["CategoryName"].ToString(), PDF_FONT_DEFAULT));
                    arrTd1[1].HorizontalAlignment = Element.ALIGN_LEFT;
                    arrTd1[2] = new PdfPCell();
                    arrTd1[2].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[2].AddElement(new Chunk("Product:", PDF_FONT_TH));
                    arrTd1[3] = new PdfPCell();
                    arrTd1[3].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[3].AddElement(new Chunk(dr["ProductName"].ToString(), PDF_FONT_DEFAULT));
                    arrTd1[3].HorizontalAlignment = Element.ALIGN_LEFT;
                    arrTd1[4] = new PdfPCell();
                    arrTd1[4].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[4].AddElement(new Chunk("Type:", PDF_FONT_TH));
                    arrTd1[5] = new PdfPCell();
                    arrTd1[5].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[5].AddElement(new Chunk(dr["TypeSize"].ToString(), PDF_FONT_DEFAULT));
                    arrTd1[5].HorizontalAlignment = Element.ALIGN_LEFT;
                    arrTd1[6] = new PdfPCell();
                    arrTd1[6].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[6].AddElement(new Chunk(" "));
                    arrTd1[7] = new PdfPCell();
                    arrTd1[7].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[7].AddElement(new Chunk(" "));
                    arrTd1[8] = new PdfPCell();
                    arrTd1[8].Rowspan = 3;

                    Chunk cImage = new Chunk(iTextSharp.text.Image.GetInstance(Server.MapPath("~") + "\\images\\siteimages\\arrow.jpg"), 0, 0, false);
                    Anchor back = new Anchor(cImage);
                    //Anchor back = new Anchor("Go Back", PDF_FONT_NAV);
                    back.Reference = "#Products";
                    Paragraph p1 = new Paragraph();
                    p1.Add(back);
                    arrTd1[8].AddElement(p1);
                    arrTd1[8].PaddingTop = 25f;

                    PdfPCell[] arrTd2 = new PdfPCell[9];

                    arrTd2[0] = new PdfPCell();
                    arrTd2[0].AddElement(new Chunk("Media:", PDF_FONT_TH));
                    arrTd2[1] = new PdfPCell();
                    arrTd2[1].AddElement(new Chunk(dr["MediaName"].ToString(), PDF_FONT_DEFAULT));
                    arrTd2[2] = new PdfPCell();
                    arrTd2[2].AddElement(new Chunk("Section:", PDF_FONT_TH));
                    arrTd2[3] = new PdfPCell();
                    arrTd2[3].AddElement(new Chunk(dr["SectionName"].ToString(), PDF_FONT_DEFAULT));

                    arrTd2[4] = new PdfPCell();
                    arrTd2[4].AddElement(new Chunk("Page #:", PDF_FONT_TH));

                    arrTd2[5] = new PdfPCell();
                    arrTd2[5].AddElement(new Chunk(dr["Page"].ToString(), PDF_FONT_DEFAULT));
                    arrTd2[6] = new PdfPCell();
                    arrTd2[6].AddElement(new Chunk("Investment", PDF_FONT_TH));

                    arrTd2[7] = new PdfPCell();
                    arrTd2[7].AddElement(new Chunk(GetCurrency(dr["Price"].ToString()), PDF_FONT_DEFAULT));
                    PdfPRow tr1 = new PdfPRow(arrTd1);
                    PdfPRow tr2 = new PdfPRow(arrTd2);

                    pdfTable.Rows.Add(tr1);
                    pdfTable.Rows.Add(tr2);

                    //iTextSharp.text.Image cropPic = null;
                    //iTextSharp.text.Image fullPic = null;
                    foreach (PdfPRow row in pdfTable.Rows)
                    {
                        foreach (PdfPCell cell in row.GetCells())
                        {
                            if (cell != null)
                            {
                                cell.Border = Rectangle.NO_BORDER;

                            }
                        }
                    }
                    if (File.Exists(croppedImagePath)) //cropped Image
                    {
                        iTextSharp.text.Image cropPic;

                        cropPic = iTextSharp.text.Image.GetInstance(croppedImagePath);


                        if (cropPic.Width > cropPic.Height)
                        {
                            iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(360, 360);
                            cropPic.ScaleToFit(360, 360);
                        }
                        else
                        {

                            if (cropPic.Height > 360)
                            {
                                if (cropPic.Width > 360)
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(360, 360);
                                    cropPic.ScaleToFit(360, 360);
                                }
                                else
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(cropPic.Width, 360);
                                    cropPic.ScaleToFit(PdfPageSizenews.Width, 360);
                                }
                            }
                            else
                            {
                                if (cropPic.Width > 360)
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(360, cropPic.Height);
                                    cropPic.ScaleToFit(360, PdfPageSizenews.Height);
                                }
                                else
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(cropPic.Width, cropPic.Height);
                                    cropPic.ScaleToFit(PdfPageSizenews.Width, PdfPageSizenews.Height);
                                }
                            }
                        }

                        cropPic.SetAbsolutePosition(0, 0);
                        cropPic.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                        PdfPCell cell = new PdfPCell();
                        cell.BorderColor = iTextSharp.text.BaseColor.WHITE;


                        cell.AddElement(cropPic);
                        if (File.Exists(croppedImagePath) && File.Exists(fullImagePath))
                        {
                            cell.PaddingLeft = 20f;
                            cell.Colspan = 4;
                        }
                        else
                        {
                            cell.PaddingLeft = 210f;
                            cell.Colspan = 8;
                        }
                        cell.PaddingBottom = 0f;
                        cell.PaddingTop = 10f;

                        pdfTable.AddCell(cell);

                    }

                    if (File.Exists(fullImagePath)) //Full Image
                    {
                        iTextSharp.text.Image fullPic;
                        fullPic = iTextSharp.text.Image.GetInstance(fullImagePath);

                        if (fullPic.Height > 360)
                        {
                            if (fullPic.Width > 360)
                            {
                                iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(360, 360);
                                fullPic.ScaleToFit(360, 360);
                            }
                            else
                            {
                                iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(fullPic.Width, 360);
                                fullPic.ScaleToFit(PdfPageSizenews.Width, 360);
                            }
                        }
                        else
                        {
                            if (fullPic.Width > 360)
                            {
                                iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(360, fullPic.Height);
                                fullPic.ScaleToFit(360, PdfPageSizenews.Height);
                            }
                            else
                            {
                                iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(fullPic.Width, fullPic.Height);
                                fullPic.ScaleToFit(PdfPageSizenews.Width, PdfPageSizenews.Height);
                            }
                        }
                        fullPic.SetAbsolutePosition(0, 0);
                        fullPic.Alignment = iTextSharp.text.Image.ALIGN_LEFT;



                        PdfPCell cell = new PdfPCell();
                        cell.BorderColor = iTextSharp.text.BaseColor.WHITE;


                        cell.AddElement(fullPic);
                        if (File.Exists(croppedImagePath) && File.Exists(fullImagePath))
                        {
                            cell.PaddingLeft = 20f;
                            cell.Colspan = 4;
                        }
                        else
                        {
                            cell.PaddingLeft = 210f;
                            cell.Colspan = 8;
                        }
                        cell.PaddingBottom = 0f;
                        cell.PaddingTop = 10f;
                        pdfTable.AddCell(cell);
                    }



                    pdfDoc.Add(pdfTable);


                }
            }

        }


        private void CreatePDFPage_NewsDetailList(Document pdfDoc, PdfWriter writer, iTextSharp.text.Image bgImage, DataTable dtNewsDetail)
        {

            foreach (DataRow dr in dtNewsDetail.Rows)
            {

                string pdfImagePath = Server.MapPath("~") + "\\News\\Cropped\\" + dr["CropPicture"].ToString(); // Server.MapPath("~") + "\\Images\\SiteImages\\PDF.png";
                if (File.Exists(pdfImagePath))
                {
                    pdfDoc.NewPage();
                    PdfContentByte pcb1 = writer.DirectContentUnder;
                    pcb1.AddImage(bgImage);
                    Paragraph pPageHeading = new Paragraph(14.0f, "\n\n\nNEWS: " + dr["ProductName"] + "\n\n", PDF_FONT_HEADING);
                    pPageHeading.Alignment = iTextSharp.text.Element.ALIGN_LEFT;
                    pPageHeading.IndentationLeft = 330f;

                    pdfDoc.Add(pPageHeading);

                    Anchor prodAnchor = new Anchor(".");
                    prodAnchor.Name = dr["NewsLogID"].ToString();
                    Paragraph p = new Paragraph();
                    p.Add(prodAnchor);
                    pdfDoc.Add(p);

                    PdfPTable pdfTable = new PdfPTable(9);
                    pdfTable.WidthPercentage = 100;
                    var colWidthPercentages = new[] { 7f, 20f, 6f, 17f, 10f, 12f, 8f, 12f, 8f };
                    pdfTable.SetWidths(colWidthPercentages);

                    PdfPCell[] arrTd1 = new PdfPCell[9];

                    arrTd1[0] = new PdfPCell();
                    arrTd1[0].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[0].AddElement(new Chunk("Category:", PDF_FONT_TH));

                    arrTd1[1] = new PdfPCell();
                    arrTd1[1].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[1].AddElement(new Chunk(dr["CategoryName"].ToString(), PDF_FONT_DEFAULT));

                    arrTd1[2] = new PdfPCell();
                    arrTd1[2].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[2].AddElement(new Chunk("Product:", PDF_FONT_TH));

                    arrTd1[3] = new PdfPCell();
                    arrTd1[3].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[3].AddElement(new Chunk(dr["ProductName"].ToString(), PDF_FONT_DEFAULT));

                    arrTd1[4] = new PdfPCell();
                    arrTd1[4].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[4].AddElement(new Chunk("Type:", PDF_FONT_TH));

                    arrTd1[5] = new PdfPCell();
                    arrTd1[5].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[5].AddElement(new Chunk(dr["TypeSize"].ToString(), PDF_FONT_DEFAULT));

                    arrTd1[6] = new PdfPCell();
                    arrTd1[6].BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(230, 230, 230));
                    arrTd1[6].AddElement(new Chunk(""));

                    arrTd1[7] = new PdfPCell();
                    arrTd1[7].AddElement(new Chunk(""));

                    arrTd1[8] = new PdfPCell();
                    arrTd1[8].Rowspan = 3;
                    Chunk cImage = new Chunk(iTextSharp.text.Image.GetInstance(Server.MapPath("~") + "\\images\\siteimages\\arrow.jpg"), 0, 0, false);
                    Anchor back = new Anchor(cImage);

                    //Anchor back = new Anchor("Go Back", PDF_FONT_NAV);
                    back.Reference = "#News";
                    Paragraph p1 = new Paragraph();
                    p1.Add(back);
                    arrTd1[8].AddElement(p1);
                    arrTd1[8].PaddingTop = 25f;

                    PdfPCell[] arrTd2 = new PdfPCell[9];

                    arrTd2[0] = new PdfPCell();
                    arrTd2[0].AddElement(new Chunk("Media:", PDF_FONT_TH));

                    arrTd2[1] = new PdfPCell();
                    arrTd2[1].AddElement(new Chunk(dr["MediaName"].ToString(), PDF_FONT_DEFAULT));

                    arrTd2[2] = new PdfPCell();
                    arrTd2[2].AddElement(new Chunk("Section:", PDF_FONT_TH));

                    arrTd2[3] = new PdfPCell();
                    arrTd2[3].AddElement(new Chunk(dr["SectionName"].ToString(), PDF_FONT_DEFAULT));

                    arrTd2[4] = new PdfPCell();
                    arrTd2[4].AddElement(new Chunk("Page Number:", PDF_FONT_TH));

                    arrTd2[5] = new PdfPCell();
                    arrTd2[5].AddElement(new Chunk(dr["Page"].ToString(), PDF_FONT_DEFAULT));

                    arrTd2[6] = new PdfPCell();
                    arrTd2[6].AddElement(new Chunk("Investment", PDF_FONT_TH));

                    arrTd2[7] = new PdfPCell();
                    arrTd2[7].AddElement(new Chunk(GetCurrency(dr["Price"].ToString()), PDF_FONT_DEFAULT));
                    PdfPRow tr1 = new PdfPRow(arrTd1);
                    PdfPRow tr2 = new PdfPRow(arrTd2);

                    pdfTable.Rows.Add(tr1);
                    pdfTable.Rows.Add(tr2);


                    foreach (PdfPRow row in pdfTable.Rows)
                    {
                        foreach (PdfPCell cell in row.GetCells())
                        {
                            if (cell != null)
                            {
                                cell.Border = Rectangle.NO_BORDER;

                            }

                        }
                    }



                    if (File.Exists(pdfImagePath))
                    {
                        iTextSharp.text.Image pdfPic = iTextSharp.text.Image.GetInstance(pdfImagePath);

                        if (pdfPic.Width > pdfPic.Height)
                        {
                            if (pdfPic.Height > 360)
                            {
                                iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(pdfPic.Width, pdfPic.Height);
                                pdfPic.ScaleToFit(PdfPageSizenews.Width, 360);
                            }
                            else
                            {
                                if (pdfPic.Width > 300)
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(pdfPic.Width, pdfPic.Height);
                                    pdfPic.ScaleToFit(PdfPageSizenews.Width, PdfPageSizenews.Height);
                                }
                                else
                                {
                                    iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(pdfPic.Width, pdfPic.Height);
                                    pdfPic.ScaleToFit(360, 360);

                                }
                            }
                        }

                        else
                        {

                            iTextSharp.text.Rectangle PdfPageSizenews = new iTextSharp.text.Rectangle(pdfPic.Width, pdfPic.Height);
                            pdfPic.ScaleToFit(360, 360);

                        }


                        pdfPic.SetAbsolutePosition(0, 0);
                        pdfPic.Alignment = iTextSharp.text.Image.ALIGN_LEFT;

                        Anchor lnk = new Anchor("PDF Link");
                        string url = "";
                        if (AppUser.GetCountry() == 58)
                        {
                            url = "http://mediamonitor.do/News/PDF/" + dr["PDFName"].ToString();

                        }

                        else
                        {
                            url = "http://mediamonitor.com.tt/News/PDF/" + dr["PDFName"].ToString();
                        }

                        pdfPic.Annotation = new Annotation(0, 0, 0, 0, url);

                        PdfPCell cell = new PdfPCell();
                        cell.BorderColor = iTextSharp.text.BaseColor.WHITE;

                        cell.Colspan = 8;
                        cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;

                        cell.AddElement(pdfPic);
                        cell.PaddingLeft = 210f;
                        cell.PaddingBottom = 0f;
                        cell.PaddingTop = 10f;
                        pdfTable.AddCell(cell);

                    }

                    pdfDoc.Add(pdfTable);

                }

            }

        }

        #endregion

        protected void btnDownloadAll_Clicked(object sender, EventArgs e)
        {

            Int32 MediaType = 0;
            Int32 CategoryID = 0;
            String CategoryName = String.Empty;
            MediaType = Utility.ToInt(Utility.GetRequestedVal("mtc", "0"));
            CategoryID = Utility.ToInt(Utility.GetRequestedVal("cc", "0"));
            DataTable dt = RfController.GetVideosAudiosCategory(MediaType, CategoryID);

            if (dt.Rows.Count > 0)
            {
                #region[Zip Format]
                Response.Clear();
                // no buffering - allows large zip files to download as they are zipped
                Response.BufferOutput = false;
                String filePath = String.Empty;
                String filePath1 = String.Empty;
                String downloadFileName = dt.Rows[0]["CategoryName"].ToString().Replace("/", "") + ".zip";
                downloadFileName = downloadFileName.Replace(" ", "_");

                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + downloadFileName);

                using (ZipFile zip = new ZipFile())
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        String filePathCheck = String.Empty;
                        String filePathCheck1 = String.Empty;
                        String CatName = String.Empty;
                        filePath = row["CropPicture"].ToString();
                        filePath1 = row["FullPagePicture"].ToString();
                        CatName = row["CategoryName"].ToString().Replace("/", "");
                        CatName = CatName.Replace(" ", "_"); ;

                        filePathCheck = Server.MapPath("../news/Cropped/" + filePath);
                        filePathCheck1 = Server.MapPath("../news/FullPage/" + filePath1);
                        if (filePath != "")
                        {
                            if (File.Exists(filePathCheck))
                            {
                                try
                                {
                                    zip.AddFile(filePathCheck, CatName);
                                }
                                catch { }
                            }
                        }

                        if (filePath1 != "")
                        {
                            if (File.Exists(filePathCheck1))
                            {
                                try
                                {
                                    zip.AddFile(filePathCheck1, CatName);
                                }
                                catch { }
                            }
                        }

                    }
                    zip.Save(Response.OutputStream);
                }
                Response.Close();
                Response.End();


                #endregion
            }
            else
            {
                AjaxFuncs.MsgBox(this.Page, "No record exists!");
            }
        }

        protected void btnDownloadAllProduct_Clicked(object sender, EventArgs e)
        {

            Int32 MediaType = 0;
            Int32 ProductID = 0;
            String ProductName = String.Empty;
            MediaType = Utility.ToInt(Utility.GetRequestedVal("mtc", "0"));
            ProductID = Utility.ToInt(Utility.GetRequestedVal("prod", "0"));
            DataTable dt = RfController.GetVideosAudiosProduct(MediaType, ProductID);

            if (dt.Rows.Count > 0)
            {
                #region[Zip Format]
                Response.Clear();
                // no buffering - allows large zip files to download as they are zipped
                Response.BufferOutput = false;
                String filePath = String.Empty;
                String filePath1 = String.Empty;
                String downloadFileName = dt.Rows[0]["BrandName"].ToString().Replace("/", "") + ".zip";
                downloadFileName = downloadFileName.Replace(" ", "_");

                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + downloadFileName);

                using (ZipFile zip = new ZipFile())
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        String filePathCheck = String.Empty;
                        String filePathCheck1 = String.Empty;
                        String CatName = String.Empty;
                        filePath = row["CropPicture"].ToString();
                        filePath1 = row["FullPagePicture"].ToString();
                        CatName = row["BrandName"].ToString().Replace("/", "");
                        CatName = CatName.Replace(" ", "_"); ;

                        filePathCheck = Server.MapPath("../news/Cropped/" + filePath);
                        filePathCheck1 = Server.MapPath("../news/FullPage/" + filePath1);
                        if (filePath != "")
                        {
                            if (File.Exists(filePathCheck))
                            {
                                try
                                {
                                    zip.AddFile(filePathCheck, CatName);
                                }
                                catch { }
                            }
                        }

                        if (filePath1 != "")
                        {
                            if (File.Exists(filePathCheck1))
                            {
                                try
                                {
                                    zip.AddFile(filePathCheck1, CatName);
                                }
                                catch { }
                            }
                        }

                    }
                    zip.Save(Response.OutputStream);
                }
                Response.Close();
                Response.End();


                #endregion
            }
            else
            {
                AjaxFuncs.MsgBox(this.Page, "No record exists!");
            }

        }
    }
}